package org.softmed.ATComm;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.softmed.ATComm.sms.SMS;
import org.softmed.ATComm.sms.SMSBatch;

public class ATControlFacade {

	SerialConnectionManager serialConnectionManager = new DefaultRXTXSerialConnectionManager();
	SMSToATTranslator translator = new DefaultSMSToATTranslator();

	public ATControlFacade() {

	}

	public synchronized List<String> getSerialPorts() {
		return serialConnectionManager.getSerialPorts();
	}

	public synchronized void disconnect() throws Throwable {
		serialConnectionManager.disconnect();
	}

	public synchronized void connect() throws Throwable {
		serialConnectionManager.connect();
	}

	public synchronized void setSerialPortName(String port) {
		serialConnectionManager.setSerialPortName(port);
	}
	
	public synchronized String getSerialPortName() {
		return serialConnectionManager.getSerialPortName();
	}

	public synchronized void reconnect() throws Throwable {
		disconnect();
		connect();
	}

	public synchronized void sendSMS(String number, String message)
			throws Throwable {
		connect();
		InputStream in = serialConnectionManager.getInputStream();
		OutputStream out = serialConnectionManager.getOutputStream();
		translator.sendSMS(number, message, in, out);
		in.close();
		out.close();
		disconnect();
	}

	public void send(SMS sms) throws Throwable {
		sendSMS(sms.getNumber(), sms.getMessage());
	}

	public synchronized void send(SMSBatch batch) throws Throwable {
		connect();
		InputStream in = serialConnectionManager.getInputStream();
		OutputStream out = serialConnectionManager.getOutputStream();

		String prefix = batch.getPrefix();
		prefix = (prefix == null ? "" : prefix);
		List<SMS> list = batch.getSmsList();
		for (SMS sms : list) {
			translator.sendSMS(prefix + sms.getNumber(), sms.getMessage(), in,
					out);
		}

		in.close();
		out.close();
		disconnect();
	}

	public SerialConnectionManager getSerialConnectionManager() {
		return serialConnectionManager;
	}

	public void setSerialConnectionManager(
			SerialConnectionManager serialConnectionManager) {
		this.serialConnectionManager = serialConnectionManager;
	}

	public SMSToATTranslator getTranslator() {
		return translator;
	}

	public void setTranslator(SMSToATTranslator translator) {
		this.translator = translator;
	}

}
